package org.gthelper.handler;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;

import org.gthelper.data.DataGeter;
import org.gthelper.database.UserInfo;
import org.gthelper.database.UserinfoStatus;
import org.gthelper.error.ErrorCode;
import org.gthelper.order.OrderInfo;
import org.gthelper.security.IchkID;
import org.gthelper.security.ValidationRSA;
import org.gthelper.testtools.Printer;

/**
 * 用户注册
 * @author pig
 */
public class Reg extends Handler
{

	@Override
	public int handle(OrderInfo orderinfo) {
		// TODO 自动生成的方法存根
		//get id
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		DataGeter dg = new DataGeter();
		int errcode=dg.getData(orderinfo.orderStream, baos);
		if(errcode!=ErrorCode.NORMAL)return errcode;
		byte[] userid = baos.toByteArray();
		baos.reset();
		Printer.printnote("inreg");
		//get encrypt password
		errcode = dg.getData(orderinfo.orderStream, baos);
		if(errcode!=ErrorCode.NORMAL)return errcode;
		byte[] encryptPw = baos.toByteArray();
		baos.reset();
		
		//get userkey
		errcode = dg.getData(orderinfo.orderStream, baos);
		if(errcode!=ErrorCode.NORMAL)return errcode;
		byte[] userkey = baos.toByteArray();
		baos.reset();
		
		IchkID chkid = new ValidationRSA();
		
		try {
			String usrid=new String(userid,"UTF-8");
			UserInfo userinfo=null;
			
			try {
				userinfo = UserInfo.getUserInfobyID(usrid);
			} catch (Exception e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
				return ErrorCode.DATABASEERR;
			}
			
			if(userinfo==null)return ErrorCode.NONEPRIKEY;
			
			byte[] prikey = IchkID.decryptBASE64((userinfo.getprivatekey_server()));
			if(prikey==null)return ErrorCode.NONEPRIKEY;
			byte[] pw = chkid.decryptByPrivateKey(encryptPw, prikey);
			byte[] pwSHA = chkid.encryptSHA(pw);
			
			//update user status
			userinfo.setpublickey_user(IchkID.encryptBASE64(userkey));
			userinfo.setshapw(new String(pwSHA,"UTF-8"));
			userinfo.setstatus_login(UserinfoStatus.Login);
			userinfo.setlastcalltime(new Timestamp(System.currentTimeMillis()));
			
			if(!userinfo.UpdateUserInfo())return ErrorCode.DATABASEERR;
			
			Printer.printnote("in Reg");
			Printer.printnote("in Reg");
			//向用户返回成功
			DataOutputStream dos = new DataOutputStream(orderinfo.mainOutput);
			dos.writeLong(1);
			
			return ErrorCode.NORMAL;
				
		} catch (UnsupportedEncodingException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			return ErrorCode.UNKNOWN;
		}
		return ErrorCode.NORMAL;
	}
	
	
	
}